package com.yoo.module_base.view.index.slideview.hp

import androidx.recyclerview.widget.RecyclerView
import com.yoo.module_base.view.index.slideview.IndexSlideCardLayoutManager

class IndexSlideCardDataObserver(recyclerView: RecyclerView) : RecyclerView.AdapterDataObserver() {
    private val recyclerView: RecyclerView

    init {
        this.recyclerView = recyclerView
    }

    override fun onChanged() {
        val manager: IndexSlideCardLayoutManager = cardStackLayoutManager
        manager.topPosition = 0
    }

    override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
        // Do nothing
    }

    override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
        // Do nothing
    }

    override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
        // Do nothing
    }

    override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
        val manager: IndexSlideCardLayoutManager = cardStackLayoutManager
        val topPosition: Int = manager.topPosition
        if (manager.getItemCount() == 0) {
            manager.topPosition = 0
        } else if (positionStart < topPosition) {
            val diff = topPosition - positionStart
            manager.topPosition = (Math.min(topPosition - diff, manager.getItemCount() - 1))
        }
    }

    override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
        val manager: IndexSlideCardLayoutManager = cardStackLayoutManager
        manager.removeAllViews()
    }

    private val cardStackLayoutManager: IndexSlideCardLayoutManager
        private get() {
            val manager: RecyclerView.LayoutManager? = recyclerView.layoutManager
            if (manager is IndexSlideCardLayoutManager) {
                return manager as IndexSlideCardLayoutManager
            }
            throw IllegalStateException("CardStackView must be set CardStackLayoutManager.")
        }
}
